package org.advanced.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author John.zhang
 * @version Id: NioSocketClient, v 1.0 2020/12/17 11:10 ZhiYong Exp $
 */
public class NioSocketClient {


    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            //解决客户端的IO阻塞，设置为非阻塞(如果这里使用非阻塞客户端，那么就收不到服务端的消息了)
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress("localhost", 8080));
            //非阻塞情况下 不一定等到连接建立再执行，所以要判断
            if (socketChannel.isConnectionPending()) {
                socketChannel.finishConnect();
            }
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put("Hello,I'm SocketChannel Client1".getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            //读取服务端返回的数据
            byteBuffer.clear();
            int read = socketChannel.read(byteBuffer);
            if (read > 0) {
                System.out.println("收到服务端的消息：" + new String(byteBuffer.array()));
            } else {
                System.out.println("服务端数据还未返回");
            }
            //避免客户端运行结束导致[远程主机强迫关闭了一个现有的连接]的错误，或者用上面的方式读取
            //System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
